<template>
  <el-card>
        <div slot="header">
          <my-bread-crumb>个人设置</my-bread-crumb>
        </div>

        <el-row>
          <el-col :span="16">
              <!-- 表单 -->
              <el-form label-width="80px" :rules="rules" :model="userData" ref="ruleForm" >
                <el-form-item label="编号">
                  <span>{{userData.id}}</span>
                </el-form-item>
                 <el-form-item label="手机">
                  <span>{{userData.mobile}}</span>
                </el-form-item>
                 <el-form-item label="名称" prop="name">
                  <el-input v-model="userData.name" />
                </el-form-item>
                 <el-form-item label="简介" prop="intro">
                  <el-input type="textarea" v-model="userData.intro" />
                </el-form-item>
                 <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userData.email" />
                </el-form-item>
                <el-form-item>
                  <el-button @click="hClick">保存设置</el-button>
                </el-form-item>
              </el-form>
          </el-col>
          <el-col :span="8">
            <el-upload
              class="avatar-uploader"
              action=""
              name="image"
              :show-file-list="false"
              :http-request="uploadFn"
              :before-upload="beforeAvatarUpload">
              <img v-if="url" :src="url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-row>
      </el-card>
</template>

<script>
export default {
  name: 'settings',
  data: function () {
    var email = function (rule, value, callback) {
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z]{2,4}$/
      if (value === '') {
        callback(new Error('请填写邮箱'))
      } else if (!regEmail.test(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    return {
      userData: {
        email: '',
        id: '',
        intro: '',
        mobile: '',
        name: '',
        photo: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        intro: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ],
        email: [{ validator: email, trigger: 'blur' }]
      },
      url: null
    }
  },
  mounted () {
    this.getUserFn()
  },
  methods: {
    async getUserFn () { // 获取用户数据
      await this.$axios.get('/mp/v1_0/user/profile').then(res => {
        console.log(res)
        this.userData = res.data.data
        this.url = res.data.data.photo
      }).catch(err => { console.log(err) })
    },
    hClick () {
      this.$refs.ruleForm.validate(okk => {
        // 验证成功
        if (okk) {
          this.saveUserFn()
        }
      })
    },
    async saveUserFn () { // 保存设置
      try {
        const res = await this.$axios({
          method: 'patch',
          url: '/mp/v1_0/user/profile',
          data: {
            name: this.userData.name,
            intro: this.userData.intro,
            email: this.userData.email
          }
        })
        this.$message.success('保存成功')
        console.log(res)
        this.$eventBus.$emit('userName', this.userData.name)
      } catch (err) {
        console.log(err)
        this.$message.error('保存失败')
      }
    },
    beforeAvatarUpload (file) { // 上传头像前
      if (file.type !== 'image/jpeg' || file.size / 1024 / 1024 >= 2) {
        this.$message.error('请上传jpg格式的图片(小于2MB)')
        return false
      }
    },
    async uploadFn (obj) { // 上传头像
      try {
        console.log('上传中...', obj)
        const fd = new FormData()
        // 向fd中添加一个参数
        fd.append('photo', obj.file)
        const res = await this.$axios({
          method: 'patch',
          url: '/mp/v1_0/user/photo',
          data: fd
        })
        this.$message.success('头像更新成功')
        console.log(res)
        this.url = res.data.data.photo
        this.$eventBus.$emit('userPhoto', this.url)
      } catch (err) {
        console.log(err)
        this.$message.error('头像更新失败')
      }
    }
  }

}
</script>

<style lang="less" scoped>

.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #ddd;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
